<template>
  <div class="canvas-container">
    <canvas
      ref="canvasRef"
      @mousedown="startDrawing"
      @mousemove="draw"
      @mouseup="stopDrawing"
      @mouseleave="stopDrawing"
      @touchstart="handleTouchStart"
      @touchmove="handleTouchMove"
      @touchend="handleTouchEnd"
    ></canvas>
    
    <div class="result-container" v-if="aiGuessResult">
      <h3>AI猜测结果:</h3>
      <p class="guess-result">{{ aiGuessResult }}</p>
    </div>
    
    <div class="toolbar">
      <input type="color" v-model="currentColor" />
      <input
        type="range"
        min="1"
        max="20"
        v-model="currentWidth"
      />
      <button @click="clearCanvas">清空</button>
      <button @click="undo">撤销</button>
      <button @click="redo">重做</button>
      <button @click="submitDrawing" :disabled="isSubmitting">
  <span v-if="isSubmitting">提交中...</span>
  <span v-else>提交画作</span>
</button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, onUnmounted, shallowRef } from 'vue';

const canvasRef = ref<HTMLCanvasElement | null>(null);
const ctx = shallowRef<CanvasRenderingContext2D | null>(null);
const isDrawing = ref(false);
const currentColor = ref('#000000');
const currentWidth = ref(5);
const drawingHistory = ref<ImageData[]>([]);
const historyIndex = ref(-1);
const isSubmitting = ref(false);
const aiGuessResult = ref<string | null>(null);

// 初始化画布
onMounted(() => {
  if (canvasRef.value) {
    const canvas = canvasRef.value;
    // 设置画布尺寸
    canvas.width = 800;
    canvas.height = 600;
    // 获取上下文
    ctx.value = canvas.getContext('2d');
    if (ctx.value) {
      // 设置初始样式
      ctx.value.lineCap = 'round';
      ctx.value.lineJoin = 'round';
      // 初始化空白画布
      clearCanvas();
    }
  }
});

// 开始绘画
const startDrawing = (e: MouseEvent) => {
  if (ctx.value) {
    isDrawing.value = true;
    const { offsetX, offsetY } = e;
    ctx.value.beginPath();
    ctx.value.moveTo(offsetX, offsetY);
    ctx.value.strokeStyle = currentColor.value;
    ctx.value.lineWidth = currentWidth.value;
    // 保存当前状态
    saveCurrentState();
  }
};

// 绘制
const draw = (e: MouseEvent) => {
  if (!isDrawing.value || !ctx.value) return;
  const { offsetX, offsetY } = e;
  ctx.value.lineTo(offsetX, offsetY);
  ctx.value.stroke();
};

// 停止绘画
const stopDrawing = () => {
  if (isDrawing.value && ctx.value) {
    isDrawing.value = false;
    ctx.value.closePath();
    // 保存当前状态
    saveCurrentState();
  }
};

// 清空画布
const clearCanvas = () => {
  if (ctx.value && canvasRef.value) {
    ctx.value.clearRect(0, 0, canvasRef.value.width, canvasRef.value.height);
    // 保存空白状态
    saveCurrentState();
  }
};

// 保存当前状态
const saveCurrentState = () => {
  if (ctx.value && canvasRef.value) {
    console.log('保存当前状态前 - historyIndex:', historyIndex.value, '历史记录长度:', drawingHistory.value.length);
    // 移除历史记录中当前索引之后的所有状态
    drawingHistory.value.splice(historyIndex.value + 1);
    console.log('移除后历史记录长度:', drawingHistory.value.length);
    // 保存当前状态
    const imageData = ctx.value.getImageData(0, 0, canvasRef.value.width, canvasRef.value.height);
    drawingHistory.value.push(imageData);
    historyIndex.value = drawingHistory.value.length - 1;
    console.log('保存后 - historyIndex:', historyIndex.value, '历史记录长度:', drawingHistory.value.length);
  }
};

// 撤销
const undo = () => {
  if (historyIndex.value > 0) {
    historyIndex.value--;
    const imageData = drawingHistory.value[historyIndex.value];
    if (ctx.value) {
      ctx.value.putImageData(imageData, 0, 0);
    }
  }
};

// 重做
const redo = () => {
  console.log('尝试重做，当前historyIndex:', historyIndex.value, '历史记录长度:', drawingHistory.value.length);
  if (historyIndex.value < drawingHistory.value.length - 1) {
    historyIndex.value++;
    const imageData = drawingHistory.value[historyIndex.value];
    if (ctx.value) {
      ctx.value.putImageData(imageData, 0, 0);
      console.log('重做成功，新historyIndex:', historyIndex.value);
    }
  } else {
    console.log('没有更多可重做的历史记录');
  }
};

// 提交画作
const submitDrawing = async () => {
  if (canvasRef.value && !isSubmitting.value) {
    isSubmitting.value = true;
    aiGuessResult.value = null; // 清空之前的结果
    try {
      // 将画布转换为Base64编码
      const imageData = canvasRef.value.toDataURL('image/png');
      // 这里将图像数据发送到后端进行AI猜测
      console.log('提交画作:', imageData);
      
      // 调用后端API
      const response = await fetch('http://localhost:3000/api/guess', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ image: imageData }),
      });
      
      if (!response.ok) {
        throw new Error('服务器响应错误');
      }
      
      const data = await response.json();
      console.log('AI猜测结果:', data);
      
      // 显示AI猜测结果
      aiGuessResult.value = data.guess;
    } catch (error) {
      console.error('提交失败:', error);
      aiGuessResult.value = 'AI猜测失败，请重试';
    } finally {
      isSubmitting.value = false;
    }
  }
};

// 触摸事件处理
const handleTouchStart = (e: TouchEvent) => {
  e.preventDefault();
  if (canvasRef.value && ctx.value) {
    isDrawing.value = true;
    const touch = e.touches[0];
    const rect = canvasRef.value.getBoundingClientRect();
    const x = touch.clientX - rect.left;
    const y = touch.clientY - rect.top;
    ctx.value.beginPath();
    ctx.value.moveTo(x, y);
    ctx.value.strokeStyle = currentColor.value;
    ctx.value.lineWidth = currentWidth.value;
    saveCurrentState();
  }
};

const handleTouchMove = (e: TouchEvent) => {
  e.preventDefault();
  if (!isDrawing.value || !canvasRef.value || !ctx.value) return;
  const touch = e.touches[0];
  const rect = canvasRef.value.getBoundingClientRect();
  const x = touch.clientX - rect.left;
  const y = touch.clientY - rect.top;
  ctx.value.lineTo(x, y);
  ctx.value.stroke();
};

const handleTouchEnd = () => {
  if (isDrawing.value && ctx.value) {
    isDrawing.value = false;
    ctx.value.closePath();
    saveCurrentState();
  }
};

// 清理
onUnmounted(() => {
  canvasRef.value = null;
  ctx.value = null;
});
</script>

<style scoped>
.canvas-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin: 20px;
}

canvas {
  border: 1px solid #ccc;
  background-color: white;
  cursor: crosshair;
}

.result-container {
  margin-top: 20px;
  padding: 15px;
  border-radius: 8px;
  background-color: #f9f9f9;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
  width: 800px;
  text-align: center;
}

.guess-result {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin: 10px 0;
}

.toolbar {
  margin-top: 10px;
  display: flex;
  gap: 10px;
  padding: 10px;
  background-color: #f5f5f5;
  border-radius: 5px;
}

button {
  padding: 5px 10px;
  background-color: #165DFF;
  color: white;
  border: none;
  border-radius: 3px;
  cursor: pointer;
}

button:hover {
  background-color: #0E42D2;
}
</style>